"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.untildify = exports.isValidPath = exports.sanitizeFileName = exports.getAbsoluteFilePath = exports.isAllowedExtension = exports.getAllowedExtensions = exports.getExt = exports.getCwd = exports.splitHubSpotPath = exports.splitLocalPath = exports.convertToLocalFileSystemPath = exports.convertToUnixPath = void 0;
const path_1 = __importDefault(require("path"));
const unixify_1 = __importDefault(require("unixify"));
const extensions_1 = require("../constants/extensions");
const os_1 = __importDefault(require("os"));
function convertToUnixPath(_path) {
    return (0, unixify_1.default)(path_1.default.normalize(_path));
}
exports.convertToUnixPath = convertToUnixPath;
function convertToWindowsPath(_path) {
    const rgx = new RegExp(`\\${path_1.default.posix.sep}`, 'g');
    return path_1.default.normalize(_path).replace(rgx, path_1.default.win32.sep);
}
function convertToLocalFileSystemPath(_path) {
    switch (path_1.default.sep) {
        case path_1.default.posix.sep:
            return convertToUnixPath(_path);
        case path_1.default.win32.sep:
            return convertToWindowsPath(_path);
        default:
            return path_1.default.normalize(_path);
    }
}
exports.convertToLocalFileSystemPath = convertToLocalFileSystemPath;
function removeTrailingSlashFromSplits(parts) {
    if (parts.length > 1 && parts[parts.length - 1] === '') {
        return parts.slice(0, parts.length - 1);
    }
    return parts;
}
// Splits a filepath for local file system sources.
function splitLocalPath(filepath, pathImplementation = path_1.default) {
    if (!filepath)
        return [];
    const { sep } = pathImplementation;
    const rgx = new RegExp(`\\${sep}+`, 'g');
    const parts = pathImplementation.normalize(filepath).split(rgx);
    // Restore posix root if present
    if (sep === path_1.default.posix.sep && parts[0] === '') {
        parts[0] = '/';
    }
    return removeTrailingSlashFromSplits(parts);
}
exports.splitLocalPath = splitLocalPath;
// Splits a filepath for remote sources (HubSpot).
function splitHubSpotPath(filepath) {
    if (!filepath)
        return [];
    const rgx = new RegExp(`\\${path_1.default.posix.sep}+`, 'g');
    const parts = convertToUnixPath(filepath).split(rgx);
    // Restore root if present
    if (parts[0] === '') {
        parts[0] = '/';
    }
    return removeTrailingSlashFromSplits(parts);
}
exports.splitHubSpotPath = splitHubSpotPath;
function getCwd() {
    if (process.env.INIT_CWD) {
        return process.env.INIT_CWD;
    }
    return process.cwd();
}
exports.getCwd = getCwd;
function getExt(filepath) {
    if (typeof filepath !== 'string')
        return '';
    const ext = path_1.default.extname(filepath).trim().toLowerCase();
    return ext[0] === '.' ? ext.slice(1) : ext;
}
exports.getExt = getExt;
function getAllowedExtensions(allowList = []) {
    return new Set([...Array.from(extensions_1.ALLOWED_EXTENSIONS), ...allowList]);
}
exports.getAllowedExtensions = getAllowedExtensions;
function isAllowedExtension(filepath, allowList = []) {
    const ext = getExt(filepath);
    const allowedExtensions = getAllowedExtensions(allowList);
    return allowedExtensions.has(ext);
}
exports.isAllowedExtension = isAllowedExtension;
function getAbsoluteFilePath(_path) {
    return path_1.default.resolve(getCwd(), _path);
}
exports.getAbsoluteFilePath = getAbsoluteFilePath;
// Reserved names (Windows specific)
const reservedNames = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
// Based on the node-sanitize-filename package: https://github.com/parshap/node-sanitize-filename/blob/master/index.js
function sanitizeFileName(fileName) {
    // Windows invalid/control characters
    // eslint-disable-next-line no-control-regex
    const invalidChars = /[<>:"/|?*\x00-\x1F]/g;
    //Replace invalid characters with dash
    let sanitizedFileName = fileName.replace(invalidChars, '-');
    // Removes trailing periods and spaces for Windows
    sanitizedFileName = sanitizedFileName.replace(/[. ]+$/, '');
    //Reserved names check for Windows
    if (reservedNames.test(sanitizedFileName)) {
        sanitizedFileName = `-${sanitizedFileName}`;
    }
    return sanitizedFileName;
}
exports.sanitizeFileName = sanitizeFileName;
// Based on the node-sanitize-filename package: https://github.com/parshap/node-sanitize-filename/blob/master/index.js
function isValidPath(_path) {
    // Invalid characters excluding forward slash
    // eslint-disable-next-line no-control-regex
    const invalidChars = /[<>:"|?*\x00-\x1F]/;
    const baseName = path_1.default.basename(_path);
    if (invalidChars.test(baseName)) {
        return false;
    }
    if (reservedNames.test(baseName)) {
        return false;
    }
    return true;
}
exports.isValidPath = isValidPath;
// Based on the untildify package: https://github.com/sindresorhus/untildify/blob/main/index.js
function untildify(pathWithTilde) {
    const homeDirectory = os_1.default.homedir();
    if (typeof pathWithTilde !== 'string') {
        throw new TypeError(`Expected a string, got ${typeof pathWithTilde}`);
    }
    return homeDirectory
        ? pathWithTilde.replace(/^~(?=$|\/|\\)/, homeDirectory)
        : pathWithTilde;
}
exports.untildify = untildify;
